package cn.pzhu.dao.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.pzhu.dao.UserDAO;
import cn.pzhu.pojo.User;
import cn.pzhu.util.JDBCUtil;

public class UserDAOImp implements UserDAO{
	@Override
	public int add(User user) {
		Connection con = null;
		PreparedStatement sta = null;
		int res=0;
		try {
			con = JDBCUtil.getConnection();
			String sql = "INSERT INTO user values(?,?,?,?,?,?)";
			sta = con.prepareStatement(sql);
			sta.setString(1, user.getUsername());
			sta.setString(2, user.getPassword());
			sta.setString(3, user.getEmail());
			sta.setInt(4, user.getGender());
			sta.setString(5, user.getType());
			sta.setInt(6, user.getStatus());
			res=sta.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.Close(con,sta);
		}
		return res;
	}
	@Override
	public boolean update(User user) {
		Connection con = null;
		PreparedStatement sta = null;
		int res=0;
		try {
			con = JDBCUtil.getConnection();
			String sql = "UPDATE user SET username=?,password=?,email=?,gender=?,type=?,status=? WHERE username=?";
			sta = con.prepareStatement(sql);
			sta.setString(1, user.getUsername());
			sta.setString(2, user.getPassword());
			sta.setString(3, user.getEmail());
			sta.setInt(4, user.getGender());
			sta.setString(5, user.getType());
			sta.setInt(6, user.getStatus());
			sta.setString(7, user.getUsername());
			res=sta.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.Close(con,sta);
		}
		return res!=0;
	}
	@Override
	public User selectById(String k) {
		Connection con = null;
		PreparedStatement sta = null;
		ResultSet res = null;
		try {
			con = JDBCUtil.getConnection();
			String sql = "SELECT * FROM user where username=?";
			sta = con.prepareStatement(sql);
			sta.setString(1, k);
			res = sta.executeQuery();
			if(res.next()) {
				return new User(res.getString(1),res.getString(2),res.getString(3),res.getInt(4),res.getString(5),res.getInt(6));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.Close(con,sta,res);
		}
		return null;
	}
}
